import { createSlice } from "@reduxjs/toolkit";
import { getToken, removeToken, setToken } from "../../utils/toke";
import { getUserInfoAPI, loginAPI } from "../../apis/profile";

//用戶相關
const userStore = createSlice({
    name: 'user',
    initialState: {
        token : getToken() || '',
        userInfo: {}
    },
    reducers: {
        _setToken(state , action){
            state.token = action.payload  
            setToken(state.token)
        },
        _setUserInfo(state,action){
            state.userInfo = action.payload
        },
        _clearUserInfo(state){
            removeToken()
            state.token = ''
            state.userInfo = {}
        }
    }
})

const {_setToken,_setUserInfo,_clearUserInfo} = userStore.actions

//異步請求
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        dispatch(_setToken(res.body.token))
    }
}

const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfoAPI()
        dispatch(_setUserInfo(res.body))
    }
}

export {fetchLogin , fetchUserInfo, _clearUserInfo}
const userReducer = userStore.reducer
export default userReducer